package com.yn.pet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yn.common.utils.bean.BeanUtils;
import com.yn.pet.bus.dao.DeviceInfoDao;
import com.yn.pet.bus.entity.DeviceInfo;
import com.yn.pet.bus.enums.DeviceStatusEnum;
import com.yn.pet.controller.pc.response.DeviceGroupResponse;
import com.yn.pet.controller.pc.response.page.GroupPageResponse;
import com.yn.pet.dao.DeviceGroupDao;
import com.yn.pet.entity.AppUser;
import com.yn.pet.entity.DeviceGroup;
import com.yn.pet.entity.Pet;
import com.yn.pet.service.DeviceGroupService;
import com.yn.pet.service.PetService;
import com.yn.pet.util.AppTokenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 设备组信息表 服务实现类
 * </p>
 *
 * @author xuquanjun
 * @since 2025-07-15
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DeviceGroupServiceImpl extends ServiceImpl<DeviceGroupDao, DeviceGroup> implements DeviceGroupService {
    private final PetService petService;
    private final DeviceInfoDao deviceInfoDao;
    /**
     * 添加设备组信息
     * @param name 设备组名称
     */
    @Override
    public void saveGroup(String name) {
        //获取当前登录用户信息
        AppUser appUser = AppTokenUtil.getAppUser();
        if(appUser==null){
            throw new RuntimeException("当前用户未登录");
        }
        // 去除名称前后的空格
         name = name.trim();
        Long userId = appUser.getAppUserId();
        LambdaQueryWrapper<DeviceGroup> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(DeviceGroup::getName, name)
                .eq(DeviceGroup::getUserId, userId);
        DeviceGroup one = baseMapper.selectOne(lambdaQuery);
        if(one!=null){
            throw new RuntimeException("当前用户已存在此设备组");
        }
        DeviceGroup deviceGroup = new DeviceGroup();
        deviceGroup.setName(name);
        deviceGroup.setUserId(userId);
        deviceGroup.setCreateBy(userId);
        deviceGroup.setUpdateBy(userId);
        this.save(deviceGroup);
    }

    /**
     * 修改设备组信息
     * @param name 设备组名称
     * @param groupId 设备组id
     * @return
     */
    @Override
    public void updateGroup(Long groupId, String name) {
        //获取用户信息
        AppUser appUser = AppTokenUtil.getAppUser();
        if (appUser == null) {
            throw new RuntimeException("当前用户未登录");
        }
        Long userId = appUser.getAppUserId();
        DeviceGroup deviceGroup = this.lambdaQuery()
                .eq(DeviceGroup::getGroupId, groupId)
                .eq(DeviceGroup::getUserId, userId)
                .one();
        if (deviceGroup == null) {
            throw new RuntimeException("当前用户未绑定此设备组");
        }
        // 去除名称前后的空格
        name = name.trim();
        //根据设备名称查询该用户设备组信息
        Long count = this.lambdaQuery()
                .eq(DeviceGroup::getName, name)
                .eq(DeviceGroup::getUserId, userId)
                .ne(DeviceGroup::getGroupId, groupId)
                .count();
        if (count > 0) {
            throw new RuntimeException("当前用户已存在此设备组");
        }
        deviceGroup.setName(name);
        deviceGroup.setUpdateBy(userId);
        updateById(deviceGroup);

    }

    /**
     * 删除设备组
     * @param groupId 设备组id
     * @return
     */
    @Override
    public void removeGroup(Long groupId) {
        //获取用户id
        AppUser appUser = AppTokenUtil.getAppUser();
        if(appUser==null){
            throw new RuntimeException("当前用户未登录");
        }
        Long userId = appUser.getAppUserId();
        //根据用户id查询该用户的分组数量
        Long groupCount = this.lambdaQuery().eq(DeviceGroup::getUserId, userId).count();
        if (groupCount <= 1) {
            throw new RuntimeException("用户至少需要一个设备组");
        }
        //根据设备组id查看该组是否绑定了设备
        Long count = petService.lambdaQuery().eq(Pet::getGroupId, groupId).eq(Pet::getDataStatus, 1)
                .isNull(Pet::getUnBindTime).count();
        if (count > 0) {
            throw new RuntimeException("请先解除设备组绑定的设备");
        }
        removeById(groupId);
    }

    /**
     * 分页查询设备组信息
     * @param currentPage 当前页
     * @param pageSize 每页数量
     * @return 设备组列表
     */
    @Override
    public GroupPageResponse pageList1(Integer currentPage, Integer pageSize) {
        //获取用户信息
        AppUser appUser = AppTokenUtil.getAppUser();
        if(appUser==null){
            throw new RuntimeException("当前用户未登录");
        }
        GroupPageResponse groupPageResponse = new GroupPageResponse();
        Long userId = appUser.getAppUserId();
        //根据用户id查询该用户绑定的设备数量
        List<Pet> pets = petService.listByUserId(userId);
        int deviceTotalCount =0;
        if(CollectionUtils.isEmpty(pets)){
            log.info("用户没有绑定设备");
            //用户总设备数量
            groupPageResponse.setDeviceTotalCount(deviceTotalCount);
        }else{
            deviceTotalCount =pets.size();
            groupPageResponse.setDeviceTotalCount(deviceTotalCount);
        }

        //以小组id为key,List<Pet>为value的一对多形式转map
        Map<Long, List<Pet>> petMap = pets.stream().collect(Collectors.groupingBy(Pet::getGroupId));
        //获取设备id集合
        //构建查询条件
        LambdaQueryWrapper<DeviceGroup> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(DeviceGroup::getUserId, userId);
        IPage<DeviceGroup> page = page(new Page<>(currentPage, pageSize), lambdaQuery);
        List<DeviceGroup> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return null;
        }
        ArrayList<DeviceGroupResponse> responses = new ArrayList<>(records.size());
        for (DeviceGroup deviceGroup : records) {
            DeviceGroupResponse deviceGroupResponse = new DeviceGroupResponse();
            BeanUtils.copyProperties(deviceGroup, deviceGroupResponse);
            //每个设备组绑定的设备数量
            List<Pet> petList = petMap.get(deviceGroup.getGroupId());
            deviceGroupResponse.setDeviceCount(CollectionUtils.isEmpty(petList)?0:petList.size());
            responses.add(deviceGroupResponse);
        }
        groupPageResponse.setRecords(responses);
        groupPageResponse.setTotal(page.getTotal());
        groupPageResponse.setSize(page.getSize());
        groupPageResponse.setPages(page.getPages());
        groupPageResponse.setCurrent(page.getCurrent());
        groupPageResponse.setOptimizeCountSql(page.optimizeCountSql());

        return groupPageResponse;
    }

    /**
     * 设备组详情
     * @param groupId 设备组Id
     * @return 设备组信息
     */
    @Override
    public DeviceGroupResponse getGroupInfo(Long groupId) {

        //获取用户信息
        AppUser appUser = AppTokenUtil.getAppUser();
        if(appUser==null){
            throw new RuntimeException("当前用户未登录");
        }
        Long userId = appUser.getAppUserId();
        DeviceGroup one = lambdaQuery()
                .eq(DeviceGroup::getGroupId, groupId)
                .eq(DeviceGroup::getUserId, userId)
                .one();
        if (one==null){
            throw new RuntimeException("当前用户未查询到设备组信息");
        }
        DeviceGroupResponse response = new DeviceGroupResponse();
        BeanUtils.copyProperties(one, response);
        return response;
    }
}
